package com.bardsoftware.foronuvolo.server;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.List;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;

import com.bardsoftware.foronuvolo.client.TagService;
import com.bardsoftware.foronuvolo.data.Discussion;
import com.bardsoftware.foronuvolo.data.DiscussionTag;
import com.bardsoftware.foronuvolo.data.ForumUser;
import com.bardsoftware.foronuvolo.data.Message;
import com.google.appengine.api.labs.taskqueue.QueueFactory;
import com.google.appengine.api.labs.taskqueue.TaskHandle;
import com.google.appengine.api.labs.taskqueue.TaskOptions;
import com.google.gdata.util.common.base.CharEscapers;
import com.google.gwt.user.server.rpc.RemoteServiceServlet;

@SuppressWarnings("serial")
public class TagServiceImpl  extends RemoteServiceServlet
	implements TagService {

	@Override
	public String addTagName(String name) throws IllegalArgumentException {
		if (!getThreadLocalRequest().getRequestURL().toString().startsWith(ForoNuvoloConstants.FORUM_DOMAIN)) {
	        return null;
	    }
	    ForumUser user = com.bardsoftware.foronuvolo.server.UserService.getUser(getThreadLocalRequest());
	    if (!user.canWrite()) {
	        return null;
	    }
	    if(name.equals("")){
	    	return null;
	    }
	    DiscussionTag newTag = DiscussionTag.findByName(name);
        if (newTag != null) {
            return null;
        }
        newTag = new DiscussionTag(name);
        newTag.save();
	    return newTag.getName();
	}

	@Override
	public List<String> getAllTagsName() throws IllegalArgumentException {
		if (!getThreadLocalRequest().getRequestURL().toString().startsWith(ForoNuvoloConstants.FORUM_DOMAIN)) {
	        return null;
	    }
	    ForumUser user = com.bardsoftware.foronuvolo.server.UserService.getUser(getThreadLocalRequest());
	    if (!user.canWrite()) {
	        return null;
	    }
		List<String> res = new ArrayList<String>();
		Collection<DiscussionTag> discussionTags = DiscussionTag.getAllTags();
		for (DiscussionTag discTag : discussionTags) {
			res.add(discTag.getName());
		}
		return res ;
	}

}
